//
//  NotificationsHelper.m
//  UADE-Mobile
//
//  Created by Nico on 06/06/12.
//  Copyright (c) 2012 DG. All rights reserved.
//

#import "NotificationsHelper.h"
#import "AppDelegate.h"
#import "NotificationsViewController.h"

@implementation NotificationsHelper
@synthesize test;

int intentos;


-(void)notificationArrived:(NSDictionary*) dictionary{
    @autoreleasepool {
        intentos = 0;
        NSString* notificationId = [dictionary objectForKey:@"ID"];
        NSString* resultado = nil;
        if (notificationId != nil) {
            NSString * userHash = [[NSUserDefaults standardUserDefaults] objectForKey:@"hash"];
            
            NSString * urlStr = [NSString stringWithFormat:kGetNotification, userHash, notificationId];
            NSURL* url = [[NSURL alloc] initWithString:urlStr];
            resultado = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        }
        
        if (resultado != nil) {
            
            NSMutableDictionary* resultadoMutable = [[resultado JSONValue ]mutableCopy];
            //[resultadoMutable removeObjectForKey:@"IdArchivo"];
            [self sendAck];
            [self didGetNotification:resultadoMutable];
        }
        else {
            AppDelegate* appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            [appDelegate performSelectorOnMainThread:@selector(hideProgressHUD) withObject:nil waitUntilDone:YES];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                            message:@"No se pudo recuperar la notificación del servidor." 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"Aceptar"
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
}

-(void)sendAck{
    NSString * userHash = [[NSUserDefaults standardUserDefaults] objectForKey:@"hash"];
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    intentos++;
    
    if (userHash != nil && token != nil) {
        NSString * urlStr = [NSString stringWithFormat:kAckNotification, userHash, token];
        NSURLRequest * request =  [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        
        [NSURLConnection connectionWithRequest:request delegate:self];
    }
    else {
        if (intentos > 3) {
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            BOOL ackNotSent = [prefs boolForKey:@"ackNotSent"];
            
            ackNotSent = YES;
            
            [prefs setBool:ackNotSent forKey:@"ackNotSent"];
            [prefs synchronize];
        }    
    }
}


-(void) didGetNotification:(NSDictionary*)notification{
    
    StudentModel* model = [StudentModel SharedInstance];
    NSArray* records = [model records];
    [model fetchRecordsWithDelegate:nil];

    NSDictionary* course;
    for (NSDictionary* item in records) {
        NSArray* clases = [item objectForKey:@"Clases"];
        for(NSDictionary* clase in clases){
            NSNumber* idAula = [clase objectForKey:@"IDAula"];
            if ([idAula intValue] == [[notification objectForKey:@"IdAula"] intValue]) {
                course = clase;
            }
        }
    }  
    
    if (course != nil) {
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        NSMutableArray* notificationss = (NSMutableArray*)[prefs objectForKey:@"notifications"];
        NSMutableArray* notifications = [notificationss mutableCopy];
        if (notifications == nil){
            notifications = [[NSMutableArray alloc]init];
        }
        
        [notifications addObject:notification];
        [prefs setObject:[notifications mutableCopy] forKey:@"notifications"];
        [prefs synchronize];
        
        if ([[[TTNavigator navigator] visibleViewController] respondsToSelector:@selector(invalidateModel)]) {
            [[[TTNavigator navigator] visibleViewController] performSelector:@selector(invalidateModel)];
        }
        
        [[TTNavigator navigator] openURLAction:
         [[TTURLAction actionWithURLPath:@"tt://notifications"] applyAnimated:TRUE]];
    }
    else
    {
        AppDelegate* appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate performSelectorOnMainThread:@selector(hideProgressHUD) withObject:nil waitUntilDone:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                        message:@"Notificación con datos inválidos." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Aceptar"
                                              otherButtonTitles:nil];
        [alert show];

    }
}


- (NSDate *) getJSONDate:(NSString*)jsonDate{
    NSString* header = @"/Date(";
    uint headerLength = [header length];
    
    NSString*  timestampString;
    
    NSScanner* scanner = [[NSScanner alloc] initWithString:jsonDate];
    [scanner setScanLocation:headerLength];
    [scanner scanUpToString:@")" intoString:&timestampString];
    
    NSCharacterSet* timezoneDelimiter = [NSCharacterSet characterSetWithCharactersInString:@"+-"];
    NSRange rangeOfTimezoneSymbol = [timestampString rangeOfCharacterFromSet:timezoneDelimiter];
    
    if (rangeOfTimezoneSymbol.length!=0) {
        scanner = [[NSScanner alloc] initWithString:timestampString];
        
        NSRange rangeOfFirstNumber;
        rangeOfFirstNumber.location = 0;
        rangeOfFirstNumber.length = rangeOfTimezoneSymbol.location;
        
        NSRange rangeOfSecondNumber;
        rangeOfSecondNumber.location = rangeOfTimezoneSymbol.location + 1;
        rangeOfSecondNumber.length = [timestampString length] - rangeOfSecondNumber.location;
        
        NSString* firstNumberString = [timestampString substringWithRange:rangeOfFirstNumber];
        //NSString* secondNumberString = [timestampString substringWithRange:rangeOfSecondNumber];
        
        unsigned long long firstNumber = [firstNumberString longLongValue];
        //uint secondNumber = [secondNumberString intValue];
        
        NSTimeInterval interval = firstNumber/1000;
        
        return [NSDate dateWithTimeIntervalSince1970:interval];
    }
    
    unsigned long long firstNumber = [timestampString longLongValue];
    NSTimeInterval interval = firstNumber/1000;
    
    return [NSDate dateWithTimeIntervalSince1970:interval];
}

#pragma mark - NSURLConnectionDelegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"Conexion exitosa. Respuesta: %@", [data description]);
    intentos = 0;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self sendAck];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
}


@end
